import { GlobalConfig } from '@/GlobalConfig';
import ChatHub from '@/services/chatHub';
import {
  smartStockSenseGetStockInformation,
  smartStockSensePredictTrend,
  smartStockSenseSearch,
} from '@/services/swagger/smartStockSense';
import { userStorage } from '@/userStorage';
import { Line, Stock } from '@ant-design/charts';
import { Select } from 'antd';
import { useEffect, useState } from 'react';

const { Option } = Select;

const Page = () => {
  const [selectedStock, setSelectedStock] = useState('');
  const [options, setOptions] = useState<React.ReactNode[]>([]);
  const [loading, setLoading] = useState(false);
  const [tradesData, setTradesData] = useState([]);
  const [stockName, setStockName] = useState('');
  const [stockCode, setStockCode] = useState('');
  const [stockData, setStockData] = useState<any>({});
  const [kdjData, setKDJData] = useState<any[]>([]); // 存储 KDJ 数据
  const [emptyDataMessage, setEmptyDataMessage] = useState(''); // 存储空数据提示
  const [depthData, setDepthData] = useState<any>(null); // 存储买卖盘数据
  const [predictTrendData, setPredictTrendData] = useState<any>(null); // 存储预测数据

  // 创建或获取 Hub 实例
  const token = userStorage.getToken() as string;
  const hub = ChatHub.getInstance(GlobalConfig.API_URL + '/stock/notification', token);

  // 转换函数
  const transformStockData = (data: any[]) => {
    return data.map((item) => ({
      date: item.d, // 日期
      open: item.o, // 开盘价
      close: item.c, // 收盘价
      high: item.h, // 最高价
      low: item.l, // 最低价
    }));
  };

  const handleStockChange = (value: string) => {
    setSelectedStock(value);
    triggerEvent(value);
  };

  const handleSearch = async (value: string) => {
    if (!value) {
      setOptions([]);
      return;
    }

    setLoading(true);

    try {
      const response = await smartStockSenseSearch({ keyword: value });
      const data: API.StockOutputDto[] | undefined = response.data;

      const newOptions = data
        ? data.slice(0, 10).map((stock) => (
            <Option key={stock.stockCode} value={stock.stockName}>
              {stock.stockName}
            </Option>
          ))
        : [];

      setOptions(newOptions);
    } catch (error) {
      console.error('Error fetching stocks:', error);
    } finally {
      setLoading(false);
    }
  };

  const triggerEvent = async (value: string) => {
    const allOption = options as any[];
    const selectedOption = allOption.find((x) => x.props.value === value);
    if (selectedOption) {
      const stockName = value;
      const stockCode = selectedOption.key;

      setStockName(stockName);
      setStockCode(stockCode);

      const stockInformation = await fetchStockInformation(stockCode, 0);
      const jsonStr = stockInformation?.data?.json as string;

      if (jsonStr) {
        const jsonData = JSON.parse(jsonStr);
        if (jsonData.length > 0) {
          setTradesData(jsonData);
          setEmptyDataMessage('');
        } else {
          setEmptyDataMessage('无交易数据');
          setTradesData([]);
        }
      } else {
        setEmptyDataMessage('无交易数据');
        setTradesData([]);
      }

      const kdjResponse = await fetchKDJData(stockCode);
      if (kdjResponse && kdjResponse.length > 0) {
        setKDJData(kdjResponse);
      } else {
        setKDJData([]);
      }

      const depthResponse = await fetchDepthData(stockCode);
      if (depthResponse) {
        console.log(depthResponse[0]);
        setDepthData(depthResponse[0]);
      } else {
        setDepthData(null);
      }

      const predictTrendResponse = await fetchPredictTrendData(stockCode);
      if (predictTrendResponse) {
        setPredictTrendData(predictTrendResponse);
      } else {
        setPredictTrendData(null);
      }
    }
  };

  const formatDateTime = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Month starts from 0
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day} 00:00:00`;
  };

  const fetchStockInformation = async (stockCode: string, type: API.StockDataType) => {
    const today = new Date();
    const formattedDateTime = formatDateTime(today);

    const stockInformation = await smartStockSenseGetStockInformation({
      StartTime: formattedDateTime,
      EndTime: formattedDateTime,
      Type: type,
      StockCode: stockCode,
      IsRecentDay: true,
    });

    return stockInformation;
  };

  const fetchKDJData = async (stockCode: string) => {
    const response = await fetchStockInformation(stockCode, 1); // Call to get KDJ data
    const jsonStr = response?.data?.json as string;

    if (jsonStr) {
      const jsonData = JSON.parse(jsonStr);
      return jsonData; // Assuming this data structure matches your provided example
    }
    return []; // Return an empty array if there's no data
  };

  const fetchDepthData = async (stockCode: string) => {
    const response = await smartStockSenseGetStockInformation({
      StockCode: stockCode,
      Type: 5,
    });
    const jsonStr = response?.data?.json as string;

    if (jsonStr) {
      const jsonData = JSON.parse(jsonStr);
      return jsonData; // Assuming this data structure matches your provided example
    }
    return []; // Return an empty array if there's no data
  };

  const fetchPredictTrendData = async (stockCode: string) => {
    const response = await smartStockSensePredictTrend({ stockCode: stockCode });
    return response.data;
  };

  // Format data for rendering
  const transformedData = transformStockData(tradesData);

  const stockProps = {
    data: transformedData,
    xField: 'date',
    yField: ['open', 'close', 'high', 'low'],
    fallingFill: '#26a69a',
    risingFill: '#ef5350',
  };

  const lineProps = {
    data: kdjData.map((item: any) => ({
      date: item.t, // Use "t" from KDJ data
      K: item.k, // Map "k" to K
      D: item.d, // Map "d" to D
      J: item.j, // Map "j" to J
    })),
    xField: 'date',
    yField: ['K', 'D', 'J'], // 确保指定 K、D、J 三条线
    smooth: true,
    color: ['#FF0000', '#0000FF', '#00FF00'], // K、D、J线颜色
  };

  useEffect(() => {
    if (tradesData.length > 0) {
      const newData = transformStockData(tradesData);
      setStockData((prevData: any) => ({
        ...prevData,
        [stockName]: newData, // Directly replace with new data
      }));
    }
  }, [tradesData]);

  // 订阅消息接收事件
  useEffect(() => {
    hub.ReceiveStocknNtification((message) => {
      if (message === '数据更新') {
        console.log(message);
        triggerEvent(stockCode);
      }
    });
  }, [hub]);

  // 渲染深度数据的函数
  const renderDepthData = () => {
    if (!depthData) return null;

    return (
      <div style={{ padding: '10px', border: '1px solid #ddd', marginLeft: '20px' }}>
        <h4 style={{ color: '#333' }}>买卖盘数据</h4>
        <p style={{ color: '#555' }}>时间: {depthData.t}</p>

        <div
          style={{
            border: '1px solid #007bff',
            backgroundColor: '#e7f3ff',
            padding: '10px',
            marginBottom: '10px',
          }}
        >
          <h5 style={{ color: '#007bff' }}>买入报价</h5>
          <ul>
            <li>
              买入报价 1: {depthData.pb1}，买入量: {depthData.vb1}
            </li>
            <li>
              买入报价 2: {depthData.pb2}，买入量: {depthData.vb2}
            </li>
            <li>
              买入报价 3: {depthData.pb3}，买入量: {depthData.vb3}
            </li>
            <li>
              买入报价 4: {depthData.pb4}，买入量: {depthData.vb4}
            </li>
            <li>
              买入报价 5: {depthData.pb5}，买入量: {depthData.vb5}
            </li>
          </ul>
        </div>

        <div
          style={{
            border: '1px solid #dc3545',
            backgroundColor: '#f8d7da',
            padding: '10px',
            marginBottom: '10px',
          }}
        >
          <h5 style={{ color: '#dc3545' }}>卖出报价</h5>
          <ul>
            <li>
              卖出报价 1: {depthData.ps1}，卖出量: {depthData.vs1}
            </li>
            <li>
              卖出报价 2: {depthData.ps2}，卖出量: {depthData.vs2}
            </li>
            <li>
              卖出报价 3: {depthData.ps3}，卖出量: {depthData.vs3}
            </li>
            <li>
              卖出报价 4: {depthData.ps4}，卖出量: {depthData.vs4}
            </li>
            <li>
              卖出报价 5: {depthData.ps5}，卖出量: {depthData.vs5}
            </li>
          </ul>
        </div>

        <div style={{ border: '1px solid #6c757d', backgroundColor: '#f1f1f1', padding: '10px' }}>
          <h5 style={{ color: '#6c757d' }}>预测数据</h5>
          <ul>
            <li>今天预测总数: {predictTrendData?.totalTodayPredictions}</li>
            <li>今天预测成功率: {predictTrendData?.todaysPredictionSuccessRate}%</li>
            <li>
              上次预测是否准确:{' '}
              {predictTrendData?.isLastPredictionAccurate !== undefined
                ? predictTrendData.isLastPredictionAccurate
                  ? '正确'
                  : '不正确'
                : '未知'}
            </li>
            <li>下一次预测结果: {predictTrendData?.nextPredictionResult}</li>
          </ul>
        </div>
      </div>
    );
  };

  return (
    <div style={{ display: 'flex' }}>
      <div style={{ flex: 1 }}>
        <Select
          showSearch
          placeholder="搜索股票"
          value={selectedStock}
          style={{ width: 240 }}
          onChange={handleStockChange}
          onSearch={handleSearch}
          loading={loading}
          filterOption={false}
        >
          {options.length > 0 ? options : <Option disabled>无数据</Option>}
        </Select>
        {emptyDataMessage && <div style={{ color: 'red' }}>{emptyDataMessage}</div>}
        {transformedData.length > 0 && <Stock {...stockProps} />}
        {kdjData.length > 0 && <Line {...lineProps} />}
      </div>

      {/* 显示买卖盘数据 */}
      <div style={{ width: '300px', marginLeft: '20px' }}>{renderDepthData()}</div>
    </div>
  );
};

export default Page;
